﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HungryCrowd.HelperFunctions;
using HungryCrowdLibrary;

namespace HungryCrowd
{
    public partial class login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var conn = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["HungryCrowd"].ConnectionString);
            conn.Open();

            using(var cmd =new System.Data.SqlClient.SqlCommand())
            {
                cmd.Connection = conn;
                cmd.CommandText = "SELECT * FROM dbo.Locations";
                cmd.CommandType = System.Data.CommandType.Text;

                var reader = cmd.ExecuteReader();
 
                if(reader != null)
                    while (reader.Read())
                    { 
                    
                    }
            }
        }

        #region Buttons Events
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            ValidateUser();
        }

        protected void btnReset_Click(object sender, EventArgs e)
        {

        }
        #endregion

        #region Functions
        private void ValidateUser()
        {

            if (string.IsNullOrWhiteSpace(txtUsername.Text))
                return;

            if (string.IsNullOrWhiteSpace(txtPassword.Text))
                return;

            if (Helpers.IsNewUser(txtUsername.Text))
            {
                Response.Redirect("update.aspx");
            }
            else
            {
                var sha256 = new RNGCryptoServiceProvider();

                // verify password.
                var verifyUser = API.UserManager.VerifyPassword(x => x.Username == txtUsername.Text);
                var salt = API.UserManager.GetSaltForUser(x => x.Username == txtUsername.Text);
                var loginPwdHash = Helpers.GenerateSaltedPassword(txtPassword.Text, salt);

                //this.Visible = !verifyUser.Password.SequenceEqual(loginPwdHash);
                //BitConverter.Equals(verifyUser.Password, loginPwdHash);

                if (verifyUser.Password.SequenceEqual(loginPwdHash))
                { 
                    Session.Add("userId", verifyUser.Id);
                    Response.Redirect("default.aspx");
                }
            }
        }
        #endregion
    }
}